<template>
  <div class="contract">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="合同编号" prop="contractNo">
          <el-input
            v-model="searchForm.contractNo"
            placeholder="请输入合同编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="合同类型" prop="type">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择合同类型"
            clearable
            style="width: 120px"
          >
            <el-option label="贷款合同" value="loan" />
            <el-option label="担保合同" value="guarantee" />
            <el-option label="抵押合同" value="mortgage" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="待签署" value="pending" />
            <el-option label="已签署" value="signed" />
            <el-option label="已生效" value="effective" />
            <el-option label="已到期" value="expired" />
            <el-option label="已终止" value="terminated" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <!-- <el-button type="success" @click="handleAdd">新增</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 合同列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="contractNo" label="合同编号" width="180" />
        <el-table-column label="客户姓名" width="120">
          <template #default="scope">
            {{ scope.row.customerName || getCustName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="contractType" label="合同类型" width="100">
          <template #default="scope">
            <el-tag :type="getContractTypeTag(scope.row.contractType || scope.row.type)">
              {{ getContractTypeText(scope.row.contractType || scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="合同金额" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.loanAmount || scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column label="合同期限" width="120">
          <template #default="scope">
            {{ (scope.row.loanTerm || scope.row.term) }}个月
          </template>
        </el-table-column>
        <el-table-column label="合同状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.contractStatus || scope.row.status)">
              {{ getStatusText(scope.row.contractStatus || scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="signTime" label="签署时间" width="180" />
        <el-table-column prop="effectiveTime" label="生效时间" width="180" />
        <el-table-column prop="endDate" label="到期时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="isStatusPending(scope.row)"
              link
              type="success"
              @click="handleSign(scope.row)"
            >
              签署
            </el-button>
            <el-button
              v-if="isStatusSigned(scope.row)"
              link
              type="success"
              @click="handleEffective(scope.row)"
            >
              生效
            </el-button>
            <el-button
              v-if="isStatusSignedOrEffective(scope.row)"
              link
              type="danger"
              @click="handleTerminate(scope.row)"
            >
              终止
            </el-button>
            <el-button
              link
              type="warning"
              @click="handleDownload(scope.row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 各种弹窗组件 -->
    <!-- 签署对话框 -->
    <el-dialog
      v-model="signDialogVisible"
      title="合同签署"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="signForm" label-width="100px" ref="signFormRef">
        <el-form-item label="签署方式" prop="method">
          <el-radio-group v-model="signForm.method">
            <el-radio label="offline">线下签署</el-radio>
            <el-radio label="electronic">电子签名</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="签署时间" prop="signTime">
          <el-date-picker
            v-model="signForm.signTime"
            type="datetime"
            placeholder="选择签署时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="签署附件" prop="file">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            :file-list="fileList"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传签署后的合同扫描件，仅支持PDF文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="signForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="signDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSign" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ...省略其他弹窗代码... -->
    
    <!-- 合同详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="合同详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="合同编号">{{ detail.contractNo }}</el-descriptions-item>
        <el-descriptions-item label="合同类型">
          {{ getContractTypeText(detail.contractType) }}
        </el-descriptions-item>
        <el-descriptions-item label="贷款金额">{{ formatAmount(detail.loanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="贷款期限">{{ detail.loanTerm }}个月</el-descriptions-item>
        <el-descriptions-item label="贷款用途">{{ detail.loanPurpose }}</el-descriptions-item>
        <el-descriptions-item label="还款方式">
          {{ detail.repayMethod === 1 ? '等额本息' : detail.repayMethod === 2 ? '等额本金' : '一次性还本付息' }}
        </el-descriptions-item>
        <el-descriptions-item label="担保方式">
          {{ detail.guarMethod === 1 ? '抵押担保' : detail.guarMethod === 2 ? '质押担保' : '信用担保' }}
        </el-descriptions-item>
        <el-descriptions-item label="年利率">{{ detail.interestRate }}%</el-descriptions-item>
        <el-descriptions-item label="签订日期">{{ detail.signDate }}</el-descriptions-item>
        <el-descriptions-item label="开始日期">{{ detail.startDate }}</el-descriptions-item>
        <el-descriptions-item label="到期日期">{{ detail.endDate }}</el-descriptions-item>
        <el-descriptions-item label="合同状态">
          <el-tag :type="getStatusType(detail.contractStatus)">
            {{ getStatusText(detail.contractStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="签署时间">{{ detail.signTime }}</el-descriptions-item>
        <el-descriptions-item label="生效时间">{{ detail.effectiveTime }}</el-descriptions-item>
        <el-descriptions-item label="失效时间">{{ detail.expiryTime }}</el-descriptions-item>
        <el-descriptions-item label="终止原因" :span="2">{{ detail.terminateReason || '未终止' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDownload(detail)">下载合同</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { contractApi } from '@/api/contract'
import axios from 'axios'

// 搜索表单
const searchForm = reactive({
  contractNo: '',
  customerName: '',
  type: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

// 详情数据
const detailVisible = ref(false)
const detail = ref({})

// 签署对话框
const signDialogVisible = ref(false)
const signForm = reactive({
  contractId: '',
  method: 'offline', // 默认为线下签署
  signTime: new Date().toISOString().replace('T', ' ').substring(0, 19), // 当前时间
  remark: '',
  file: null
})
const submitLoading = ref(false)
const fileList = ref([])
const currentContract = ref({})

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = () => {
  loading.value = true
  
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    contractNo: searchForm.contractNo,
    customerName: searchForm.customerName,
    type: searchForm.type,
    status: searchForm.status
  }
  
  contractApi.getList(params).then(res => {
    console.log('合同列表接口返回:', res) // 添加调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理不同的响应数据结构
      if (res.data && res.data.records) {
        // 新结构: {code:"200", msg:"操作成功", data:{records:[...], total:1, size:10, current:1}}
        tableData.value = res.data.records
        total.value = res.data.total
      } else if (res.data && res.data.rows) {
        // 旧结构: {data: {rows: [...], total: 100}}
        tableData.value = res.data.rows
        total.value = res.data.total
      } else if (Array.isArray(res.data)) {
        // 数组结构: {code: 200, data: [...]}
        tableData.value = res.data
        total.value = res.data.length
      } else {
        console.warn('未识别的合同列表数据结构:', res)
        tableData.value = []
        total.value = 0
        ElMessage.warning('获取合同列表数据格式异常')
      }
    } else {
      console.error('获取合同列表失败:', res)
      ElMessage.error(res.msg || res.message || '获取合同列表失败')
      tableData.value = []
      total.value = 0
    }
    
    loading.value = false
  }).catch(error => {
    console.error('获取合同列表出错:', error)
    ElMessage.error('获取合同列表失败')
    tableData.value = []
    total.value = 0
    loading.value = false
  })
}

// 查询
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.contractNo = ''
  searchForm.customerName = ''
  searchForm.type = ''
  searchForm.status = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  // 新增合同的逻辑
  ElMessage.info('新增合同功能待实现')
}

// 详情
const handleDetail = (row) => {
  loading.value = true
  
  // 使用指定URL直接获取合同详情
  const contractId = row.contractId || row.id
  const url = `http://localhost:8085/api/contract/${contractId}`
  
  // 获取token
  const token = localStorage.getItem('token')
  
  // 设置请求头
  const headers = {}
  if (token) {
    // 检查token是否已经包含Bearer前缀，避免重复添加
    if (token.startsWith('Bearer ')) {
      headers['Authorization'] = token
    } else {
      headers['Authorization'] = `Bearer ${token}`
    }
  }
  
  // 使用axios直接请求，并带上token
  axios.get(url, { headers })
    .then(response => {
      const res = response.data
      console.log('合同详情接口返回:', res) // 添加调试日志
      
      if (res.code === 200 || res.code === '200') {
        // 处理响应数据
        if (typeof res.data === 'object' && res.data !== null) {
          detail.value = res.data
          detailVisible.value = true
        } else {
          console.warn('未识别的合同详情数据结构:', res)
          ElMessage.warning('获取合同详情数据格式异常')
        }
      } else {
        console.error('获取合同详情失败:', res)
        ElMessage.error(res.msg || res.message || '获取合同详情失败')
      }
      
      loading.value = false
    })
    .catch(error => {
      console.error('获取合同详情出错:', error)
      ElMessage.error('获取合同详情失败')
      loading.value = false
    })
}

// 签署
const handleSign = (row) => {
  // 重置签署表单
  signForm.contractId = row.contractId || row.id
  signForm.method = 'offline'
  signForm.signTime = new Date().toISOString().replace('T', ' ').substring(0, 19)
  signForm.remark = ''
  signForm.file = null
  fileList.value = []
  
  // 记录当前操作的合同
  currentContract.value = row
  
  // 显示签署对话框
  signDialogVisible.value = true
}

// 生效
const handleEffective = (row) => {
  ElMessageBox.confirm('确认将合同标记为已生效?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    const contractId = row.contractId || row.id
    
    // 调用合同状态更新接口
    contractApi.updateStatus({
      contractId: contractId,
      status: 'effective',
      remark: '合同生效'
    }).then(res => {
      if (res.code === 200 || res.code === '200') {
        ElMessage.success('合同已生效')
        // 刷新数据
        fetchData()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
      loading.value = false
    }).catch(error => {
      console.error('更新合同状态出错:', error)
      ElMessage.error('操作失败')
      loading.value = false
    })
  }).catch(() => {
    // 用户取消操作
  })
}

// 终止
const handleTerminate = (row) => {
  ElMessageBox.prompt('请输入终止原因', '终止合同', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入终止原因',
    type: 'warning'
  }).then(({ value }) => {
    if (!value) {
      ElMessage.warning('请输入终止原因')
      return
    }
    
    loading.value = true
    const contractId = row.contractId || row.id
    
    // 调用终止合同接口
    contractApi.terminate({
      contractId: contractId,
      reason: value,
      terminateDate: new Date().toISOString().split('T')[0], // 当前日期
      remark: '用户终止合同'
    }).then(res => {
      if (res.code === 200 || res.code === '200') {
        ElMessage.success('合同已终止')
        // 刷新数据
        fetchData()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
      loading.value = false
    }).catch(error => {
      console.error('终止合同出错:', error)
      ElMessage.error('操作失败')
      loading.value = false
    })
  }).catch(() => {
    // 用户取消操作
  })
}

// 下载
const handleDownload = (row) => {
  loading.value = true;
  const contractId = row.contractId || row.id;
  const token = localStorage.getItem('token');
  // 调用下载合同接口
  axios.get(`http://localhost:8085/api/contract/down/${contractId}`, {
    responseType: 'blob' ,// 期望返回 Blob 对象
    headers: {
      'Authorization': `${token}` // 添加 Authorization 头
    }
  }).then(res => {
    // 检查响应是否为 Blob 对象
    console.log(res.data);
    console.log('Blob size:', res.data.size); // 检查 Blob 的大小

    if (res.data.size === 0) {
      throw new Error('下载的文件为空');
    }

    // 获取文件名
    const fileName = `合同_${row.contractNo || contractId}.xlsx`;

    // 创建下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(res.data);
    link.download = fileName;

    // 模拟点击下载
    document.body.appendChild(link);
    link.click();

    // 清理
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);

    ElMessage.success('Excel文件下载成功');
    loading.value = false;
  }).catch(error => {
    console.error('下载合同出错:', error);
    ElMessage.error('下载合同失败');
    loading.value = false;
  });
}


// 从响应中获取文件名
const getFileNameFromResponse = (response, defaultName) => {
  // 尝试从响应头中获取文件名
  const contentDisposition = response?.headers?.['content-disposition']
  if (contentDisposition) {
    const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition)
    if (matches && matches[1]) {
      // 解码文件名
      let fileName = matches[1].replace(/['"]/g, '')
      try {
        // 尝试解码URL编码的文件名
        fileName = decodeURIComponent(fileName)
      } catch (e) {
        console.warn('文件名解码失败:', e)
      }
      return fileName
    }
  }
  
  return defaultName
}

// 处理文件下载
const handleFileDownload = (response, fileName) => {
  // 检查response是否为Blob对象
  console.log(response.data);
  const blob = new Blob([response.data])
  
  // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = fileName
  
  // 模拟点击下载
  document.body.appendChild(link)
  link.click()
  
  // 清理
  URL.revokeObjectURL(link.href)
  document.body.removeChild(link)
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 格式化金额
const formatAmount = (amount) => {
  return amount ? `¥${amount.toLocaleString()}` : '-'
}

// 获取客户姓名
const getCustName = (row) => {
  // 通过custId获取客户姓名的逻辑，可能需要调用其他接口或从缓存获取
  return row.custName || '未知客户'
}

// 获取合同类型标签类型
const getContractTypeTag = (type) => {
  const map = {
    loan: '',
    guarantee: 'success',
    mortgage: 'warning'
  }
  return map[type] || ''
}

// 获取合同类型显示文本
const getContractTypeText = (type) => {
  const map = {
    loan: '贷款合同',
    guarantee: '担保合同',
    mortgage: '抵押合同'
  }
  return map[type] || type
}

// 获取状态类型
const getStatusType = (status) => {
  // 处理数字状态码
  if (typeof status === 'number') {
    if (status === 10) return 'info' // 待签署
    if (status === 20) return 'success' // 已签署
    if (status === 30) return 'primary' // the已生效
    if (status === 40) return 'warning' // 已到期
    if (status === 50) return 'danger' // 已终止
  }
  
  // 处理字符串状态
  const map = {
    pending: 'info',
    signed: 'success',
    effective: 'primary',
    expired: 'warning',
    terminated: 'danger',
    '10': 'info', // 待签署
    '20': 'success', // 已签署
    '30': 'primary', // 已生效
    '40': 'warning', // 已到期
    '50': 'danger' // 已终止
  }
  return map[status] || ''
}

// 获取状态显示文本
const getStatusText = (status) => {
  // 处理数字状态码
  if (typeof status === 'number') {
    if (status === 10) return '待签署'
    if (status === 20) return '已签署'
    if (status === 30) return '已生效'
    if (status === 40) return '已到期'
    if (status === 50) return '已终止'
  }
  
  // 处理字符串状态
  const map = {
    pending: '待签署',
    signed: '已签署',
    effective: '已生效',
    expired: '已到期',
    terminated: '已终止',
    '10': '待签署',
    '20': '已签署',
    '30': '已生效',
    '40': '已到期',
    '50': '已终止'
  }
  return map[status] || status
}

// 判断是否为待签署状态
const isStatusPending = (row) => {
  const status = row.contractStatus || row.status
  return status === 'pending' || status === 10 || status === '10'
}

// 判断是否为已签署状态
const isStatusSigned = (row) => {
  const status = row.contractStatus || row.status
  return status === 'signed' || status === 20 || status === '20'
}

// 判断是否为已签署或已生效状态
const isStatusSignedOrEffective = (row) => {
  const status = row.contractStatus || row.status
  return ['signed', 'effective'].includes(status) || 
         [20, 30].includes(status) || 
         ['20', '30'].includes(status)
}

// 处理签署对话框
const handleFileChange = (file) => {
  // 仅允许上传PDF文件
  const isPdf = file.raw.type === 'application/pdf'
  if (!isPdf) {
    ElMessage.error('仅支持上传PDF文件')
    fileList.value = []
    return false
  }
  
  // 限制文件大小，最大10MB
  const isLt10M = file.raw.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    fileList.value = []
    return false
  }
  
  // 记录文件对象
  signForm.file = file.raw
  return true
}

// 读取文件为base64
const readFileAsBase64 = (file) => {
  return new Promise((resolve, reject) => {
    if (!file) {
      resolve(null)
      return
    }
    
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      const base64 = reader.result.split(',')[1] // 移除data:application/pdf;base64,前缀
      resolve(base64)
    }
    reader.onerror = (error) => {
      reject(error)
    }
  })
}

// 提交签署
const submitSign = async () => {
  // 表单验证
  if (!signForm.method) {
    ElMessage.warning('请选择签署方式')
    return
  }
  
  if (!signForm.signTime) {
    ElMessage.warning('请选择签署时间')
    return
  }
  
  submitLoading.value = true
  
  try {
    // 准备签署数据
    const signData = {
      contractId: signForm.contractId,
      method: signForm.method,
      signTime: signForm.signTime,
      remark: signForm.remark
    }
    
    // 如果有上传文件，转为base64添加到请求中
    if (signForm.file) {
      const base64Content = await readFileAsBase64(signForm.file)
      signData.attachments = [
        {
          name: signForm.file.name,
          content: base64Content
        }
      ]
    }
    
    // 调用签署接口
    const res = await contractApi.sign(signData)
    
    if (res.code === 200 || res.code === '200') {
      ElMessage.success('合同签署成功')
      // 关闭对话框
      signDialogVisible.value = false
      // 刷新数据
      fetchData()
    } else {
      ElMessage.error(res.msg || '合同签署失败')
    }
  } catch (error) {
    console.error('合同签署出错:', error)
    ElMessage.error('合同签署失败')
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>